// 创建定时器，每天10点触发一次
var dataArray=[];
// chrome.alarms.create('open-url', { when: getTriggerTime(18, 55), periodInMinutes: 24 * 60 });
  // 获取今天的日期
var today = new Date().toLocaleDateString();
// 要采集的url
var url="https://traveldetail.fliggy.com/item.htm?abbucket=7&id=9191224941&ns=1&spm=a230r.1.14.7.4bb15a8fn3fo6L"
// 监听定时器触发事件
// chrome.alarms.onAlarm.addListener(function(alarm) {
//   if (alarm.name === 'open-url') {
//     // 检查是否已经采集过该URL
//     chrome.storage.local.get(['lastOpenedDate'], function(result) {
//       if (result.lastOpenedDate !== today+url) {
//         // 保存今天的日期
//         chrome.storage.local.set({ lastOpenedDate: today+url }, function() {
//           // 打开URL
//           chrome.tabs.create({ url: url});
//         });
//       }
//     });
//   }
// });
// 监听标签页更新事件
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {

  // 判断是否为淘宝商品页面
  if (changeInfo.status === 'complete' && /^https?:\/\/.*\.(taobao|fliggy)\.com\/.*$/.test(tab.url) ) {
    // if (/^https?:\/\/.*\.taobao\.com\/.*$/.test(tab.url)){
    //     chrome.tabs.sendMessage(tab.id, {action: 'getTaobaoPageInfo'});
    // }
    if (/^https?:\/\/.*\.fliggy\.com\/.*$/.test(tab.url)){
        chrome.tabs.executeScript(tabId, {file: 'content.js'}, function() {
            chrome.tabs.sendMessage(tab.id, {action: 'getfliggyPageInfo'});
          });   
    }
  }
});

// 监听来自content script的消息
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.action === 'sendPageInfo') {
      // 获取今天的日期
      const title=request.title
      var today = new Date().toLocaleDateString();
      if(!request.title && !request.price && !isNumber(request.salesCount) && !request.shopname){
        return false;
    }
    var newData = {
        title: request.title,
        price: request.price,
        salesCount: request.salesCount,
        shopname: request.shopname,
        comment:request.comment,
        day: today
      };
  // 将更新后的数据保存到本地存储中
 fetch("http://127.0.0.1:8787/index/push",{method:"POST",headers: {
    "Content-Type": "application/json",
    },
    mode: "cors",
    body:JSON.stringify(newData)}).then(function(res){
        console.log("保存成功",res);
    })
    }
  });
// 获取下一次触发时间
function getTriggerTime(hour, minute) {
    var now = new Date();
    var triggerTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), hour, minute);
    if (triggerTime <= now) {
      triggerTime.setDate(triggerTime.getDate() + 1);
    }
    return triggerTime.getTime();
  }

  function isNumber(value) {
    return !isNaN(parseFloat(value)) && isFinite(value);
  }
